import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'package:flutter/widgets.dart';
import 'package:im_app/im/page/ext/ImSpecialTextSpanBuilder.dart';
import 'package:im_app/im/util/EmojiUtil.dart';
import 'package:im_app/im/util/ImRichTextUtil.dart';

import '../../emojiOne/EmojiOne.dart';
import '../../emojiOne/EmojiPane.dart';
import '../../pojo/ImPojo.dart';
import '../../util/ImConstant.dart';
import '../model/MessageSendListModel.dart';

typedef FutureBusiness = Future<void> Function(BuildContext context);

class MessageSendView extends StatefulWidget {
  final MessageSendListModel messageSendListModel;
  _MessageSendState? _messageSendState;

  MessageSendView({required this.messageSendListModel, super.key});

  @override
  State<StatefulWidget> createState() {
    var messageSendState = _MessageSendState();
    _messageSendState = messageSendState;
    return messageSendState;
  }

  void hideEmoji() {
    _messageSendState?.hideEmoji();
  }
}

class _MessageSendState extends State<MessageSendView> {
  FocusNode userFocusNode = FocusNode();
  final TextEditingController _inputController = TextEditingController();
  bool _showAudio = false;
  bool _showEmoji = false;
  bool _showMore = false;

  @override
  Widget build(BuildContext context) {
    // var _messageSendListController = Provider.of<MessageSendListModel>(context);
    // var messageSendCubit = context.watch<MessageSendCubit>();
    return Column(children: [
      Container(
        decoration: BoxDecoration(border: Border(top: BorderSide(color: ImConstant.IM_BORDER_COLOR, width: 1))),
        padding: const EdgeInsets.only(top: 5),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _buildNode(context, '语音', _showAudio ? Icons.audiotrack_outlined : Icons.multitrack_audio_outlined,
                (context) async => showAudio(context)),
            Expanded(
              child: _showAudio ? _buildAudioNode() : buildInputText(context, _inputController),
            ),
            _buildNode(context, '显示Emoji', Icons.tag_faces_outlined, (context) async => showEmoji(context)),
            _buildNode(context, '加载更多', Icons.add_circle_outline, (context) async => showMore(context)),
            _buildNode(context, '发送', Icons.send_outlined, (context) async => await addMessage(context))
          ],
        ),
      ),
      _buildEmojiPane(context, _showEmoji),
      _buildMorePane(_showMore)
    ]);
  }

  Widget _buildEmojiPane(BuildContext context, bool showEmoji) {
    return Offstage(
      offstage: !showEmoji,
      child: EmojiPane(selectCallback: selectEmojiOneCallback, context: context,),
    );
  }

  Widget _buildMorePane(bool showPlus) {
    return Offstage(
      offstage: !showPlus,
      child: Container(
        height: 250,
        color: Colors.red,
        child: const DefaultTabController(
          initialIndex: 1,
          length: 3,
          child: Column(
            children: [
              TabBar(
                tabs: <Widget>[
                  Tab(
                    icon: Icon(Icons.cloud_outlined),
                  ),
                  Tab(
                    icon: Icon(Icons.beach_access_sharp),
                  ),
                  Tab(
                    icon: Icon(Icons.brightness_5_sharp),
                  ),
                ],
              ),
              SizedBox(
                height: 200,
                child: const TabBarView(
                  children: <Widget>[
                    Center(
                      child: Text("It's cloudy here"),
                    ),
                    Center(
                      child: Text("It's rainy here"),
                    ),
                    Center(
                      child: Text("It's sunny here"),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildEmojiPane2(bool showEmoji) {
    return Offstage(
      offstage: !showEmoji,
      child: SizedBox(
          height: 250,
          child: EmojiPicker(
              textEditingController: _inputController,
              config: Config(
                height: 256,
                checkPlatformCompatibility: true,
                emojiViewConfig: EmojiViewConfig(
                  emojiSizeMax: 28 * (foundation.defaultTargetPlatform == TargetPlatform.iOS ? 1.2 : 1.0),
                ),
                // swapCategoryAndBottomBar: false,
                skinToneConfig: const SkinToneConfig(),
                categoryViewConfig: const CategoryViewConfig(),
                bottomActionBarConfig:
                    const BottomActionBarConfig(enabled: true, showBackspaceButton: false, showSearchViewButton: false),
                searchViewConfig: const SearchViewConfig(),
              ))),
    );
  }

  @override
  void dispose() {
    _inputController.dispose();
    userFocusNode.dispose();
    super.dispose();
  }

  Widget _buildAudioNode() {
    return Container(
      decoration: const BoxDecoration(color: Colors.white),
      child: TextButton(
        onPressed: () {},
        child: const Text("按住 说话"),
      ),
    );
  }

  Widget buildInputText(BuildContext context, TextEditingController controller) {
    return ExtendedTextField(
      specialTextSpanBuilder: ImSpecialTextSpanBuilder(textStyle: const TextStyle(fontSize: 24)),
        focusNode: userFocusNode,
        controller: controller,
        decoration: InputDecoration(
            border: const OutlineInputBorder(gapPadding: 1, borderRadius: BorderRadius.all(Radius.circular(5))),
            fillColor: Colors.white,
            isCollapsed: true,
            filled: true,
            hintMaxLines: 100,
            contentPadding: const EdgeInsets.only(top: 10, right: 5, bottom: 10, left: 5),
            enabledBorder: OutlineInputBorder(
              //未选中时候的颜色
              gapPadding: 4,
              borderRadius: BorderRadius.circular(5.0),
              borderSide: const BorderSide(
                color: Colors.white,
              ),
            ),
            focusedBorder: OutlineInputBorder(
              //选中时外边框颜色
              gapPadding: 4,
              borderRadius: BorderRadius.circular(5.0),
              borderSide: const BorderSide(
                color: Colors.white,
              ),
            )),
        //maxLength: 30,//最大长度，设置此项会让TextField右下角有一个输入数量的统计字符串
        maxLines: null,
        //最大行数
        autocorrect: true,
        //是否自动更正
        autofocus: false,
        //是否自动对焦
        obscureText: false,
        //是否是密码
        textAlign: TextAlign.left,
        //文本对齐方式
        style: TextStyle(fontSize: 18.0, color: Colors.black),
        //输入文本的样式
        //inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],//允许的输入格式
        onChanged: (text) {
          //内容改变的回调
//				print('change $text');
        },
        onEditingComplete: () {
          print('test');
        },
        onSubmitted: (text) {
          //内容提交(按回车)的回调
          sendMessage(context, text);
          controller.text = '';
          print('submit $text');
        },
        enabled: true,
        //是否禁用
        extendedContextMenuBuilder: (BuildContext context, ExtendedEditableTextState editableTextState) {
          return AdaptiveTextSelectionToolbar.buttonItems(
            buttonItems: [
              ContextMenuButtonItem(onPressed: (){
                editableTextState.pasteText(SelectionChangedCause.toolbar);
              }, label: '粘贴', type: ContextMenuButtonType.custom),
            ],
            anchors: editableTextState.contextMenuAnchors,
          );
        }
        );
  }

  Widget buildInputText2(BuildContext context, TextEditingController controller) {
    return TextField(
      focusNode: userFocusNode,
      controller: controller,
      decoration: InputDecoration(
          border: const OutlineInputBorder(gapPadding: 1, borderRadius: BorderRadius.all(Radius.circular(5))),
          fillColor: Colors.white,
          isCollapsed: true,
          filled: true,
          hintMaxLines: 100,
          contentPadding: const EdgeInsets.only(top: 10, right: 5, bottom: 10, left: 5),
          enabledBorder: OutlineInputBorder(
            //未选中时候的颜色
            gapPadding: 4,
            borderRadius: BorderRadius.circular(5.0),
            borderSide: const BorderSide(
              color: Colors.white,
            ),
          ),
          focusedBorder: OutlineInputBorder(
            //选中时外边框颜色
            gapPadding: 4,
            borderRadius: BorderRadius.circular(5.0),
            borderSide: const BorderSide(
              color: Colors.white,
            ),
          )),
      //maxLength: 30,//最大长度，设置此项会让TextField右下角有一个输入数量的统计字符串
      maxLines: null,
      //最大行数
      autocorrect: true,
      //是否自动更正
      autofocus: false,
      //是否自动对焦
      obscureText: false,
      //是否是密码
      textAlign: TextAlign.left,
      //文本对齐方式
      style: const TextStyle(fontSize: 18.0, color: Colors.black),
      //输入文本的样式
      //inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],//允许的输入格式
      onChanged: (text) {
        //内容改变的回调
//				print('change $text');
      },
      onEditingComplete: () {
        print('test');
      },
      onSubmitted: (text) {
        //内容提交(按回车)的回调
        sendMessage(context, text);
        controller.text = '';
        print('submit $text');
      },
      enabled: true, //是否禁用
    );
  }

  Widget _buildNode(BuildContext context, String tooltip, IconData iconData, FutureBusiness function) {
    return Padding(
      padding: const EdgeInsets.only(right: 5, left: 5),
      child: Tooltip(
        message: tooltip,
        child: GestureDetector(
          child: Icon(iconData),
          onTap: () async => function(context),
        ),
      ),
    );
  }

  Future<void> addMessage(BuildContext context) async {
    if (_showAudio) return;
    String text = _inputController.text.trim();
    if (text == '') return;
    _inputController.text = '';
    await sendMessage(context, text);
  }

  Future<void> sendMessage(BuildContext context, String message) async {
    if (message.trim() == '') {
      return;
    }
    // var _messageSendListController = Provider.of<MessageSendListModel>(context, listen: false);
    hideEmoji();

    ImMessageType messageType = EmojiUtil.hasEmoji(message) ? ImMessageType.RichText : ImMessageType.Text;
    await widget.messageSendListModel.sendMessage(message, messageType);

    _inputController.text = "";
  }

  void showAudio(BuildContext context) {
    setState(() {
      _showAudio = !_showAudio;
      _showEmoji = false;
    });
  }

  void showEmoji(BuildContext context) {
    setState(() {
      _showEmoji = !_showEmoji;
      _showAudio = false;
      _showMore = false;
    });
    FocusScope.of(context).unfocus();
  }

  void showMore(BuildContext context) {
    setState(() {
      _showEmoji = false;
      _showAudio = false;
      _showMore = !_showMore;
    });
    FocusScope.of(context).unfocus();
  }

  void hideEmoji() {
    if (_showEmoji) {
      setState(() {
        _showEmoji = false;
      });
    }

    FocusScope.of(context).unfocus();
    print("unfocus!!!!!!!!!!!!!!!!");
  }

  selectEmojiOneCallback(BuildContext context, EmojiOne emojiOne) {
    print("emojiOne: ${emojiOne.emojiPath}");
    _inputController.text = _inputController.text + ImRichTextUtil.emojiToString(emojiOne);
  }
}
